#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from _md5 import md5
import requests
from scrapy.utils.project import get_project_settings


class ChaoJiYingVerifyCode(object):
    """
    超级鹰验证码识别：
    1、验证码类型查询 http://www.chaojiying.com/price.html
    """

    def __init__(self):
        settings = get_project_settings()
        self.user = settings.get('CJY_USER', 'charmer21')
        self.password = md5(settings.get('CJY_PWD', 'Zso2021').encode('utf8')).hexdigest()
        self.soft_id = settings.get('CJY_SOFT_ID', '899478')
        self.base_params = {
            'user': self.user,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def verify(self, image, code_type='1004'):
        """
        image: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': code_type,
        }
        params.update(self.base_params)
        files = {'userfile': ('image', open(image, 'rb'), 'image/jpeg', {'Expires': '0'})}
        r = requests.post(
            'http://upload.chaojiying.net/Upload/Processing.php',
            data=params,
            files=files,
            headers=self.headers,
            timeout=60
        )
        res = json.loads(r.content)
        if res:
            err_no = res['err_no']
            if err_no == 0:
                # 成功请求
                code = res['pic_str']
                return code
            else:
                print('verify error: %s' % res)
        else:
            print('request api error')

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

if __name__ == '__main__':
    # 1.识别验证码
    ChaoJiYingVerifyCode().verify('/work/esgcc/verify_code/111.jpg')